package ooo.reindeer.commons.utils.limit;


public class UniformSpeedLimit extends SpeedLimit {

    long originalCycle;
    long originalSpeed;

    public UniformSpeedLimit(long speed, long cycle) {
        super(speed / AFGCD(speed, cycle), cycle / AFGCD(speed, cycle));
        originalCycle = cycle;
        originalSpeed = speed;
    }

    @Override
    public void setMaxSpeed(long speed) {
        setLimit(speed,originalCycle);
    }

    @Override
    public void setCycle(long cycle) {
        setLimit(originalSpeed,cycle);
    }

    @Override
    public long getMaxSpeed() {
        return originalSpeed;
    }

    @Override
    public long getCycle() {
        return originalCycle;
    }

    @Override
    public void setLimit(long speed, long cycle) {
        originalSpeed= speed;
        originalCycle=cycle;
        super.setLimit(originalSpeed / AFGCD(originalSpeed, originalCycle), originalCycle / AFGCD(originalSpeed, originalCycle));

    }

    private static long GCD(long a, long b) {
        long max, min;
        max = Math.max(a, b);
        min = Math.min(a, b);

        if (max % min != 0) {
            return GCD(min, max % min);
        } else {
            return min;
        }

    }

    private static long AFGCD(long a, long b) {
        long value;
        if ((value = GCD(a, b)) != 1) {
            return value;
        } else {
            return Math.min(a, b);
        }
    }

    public static void main(String[] args) {
        ISpeedLimit sl = new UniformSpeedLimit(10, 1000);
        //1586243013981
        //1586243023883
        for (int i = 0; i < 100; i++) {
            sl.blockLimit();
            System.out.println(System.currentTimeMillis() + "\t" + i);
            if(i==50){
                sl.setCycle(5000);
            }
        }
        sl.shutdown();
    }
}
